#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
const std::string gfilename = "./fifo";
const int mode = 0600;
const int gdefaultId = -1;

class Init
{
public:
    Init() 
    {
        int n = ::mkfifo(gfilename.c_str(),mode);
        if (n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
        }
        std::cout << "mkfifo success" << std::endl;
    }
    ~Init()
    {
        int n  = ::unlink(gfilename.c_str());
        if (n < 0)
        {
            std::cerr << "unlink error" << std::endl;
        }
        std::cout << "unlink success" << std::endl;
    }
};
Init init;

class Server
{
public:
    Server() :_fd(gdefaultId)
    {
        OpenPipe();
    }
    bool OpenPipe()
    {
        _fd = open(gfilename.c_str(),O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "open error" << std::endl;
            return false;
        }
        return true;
    }
    //输出型参数
    void RecivePipe()
    {
        int cmd = 0;
        int n = ::read(_fd,&cmd,sizeof(cmd));
        if (n == sizeof(cmd)) 
        {

        }
        else if(n == 0)
        {
            std::cout << "write quit???" << std::endl;
            return;
        }
        else 
        {
            return;
        }
    }
    void ClosePipe()
    {
        if (_fd >= 0)
            ::close(_fd);
    }
    ~Server()
    {}
private:
    int _fd;
};

class Client
{
public:
    Client() : _fd(gdefaultId)
    {
        OpenPipe();
    }
    bool OpenPipe()
    {
        _fd = open(gfilename.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "open error" << std::endl;
            return false;
        }
        return true;
    }
    int WritePipe()
    {
        int n = 1;
        return ::write(_fd,&n,sizeof(n));
    }
    ~Client()
    {
        ClosePipe();
    }

private:
    void ClosePipe()
    {
        if (_fd >= 0)
            ::close(_fd);
    }
    int _fd;
};
